import { createRouter, createWebHistory } from 'vue-router'
import routes from './menu'
import exception from './exception'
import { useUserStore } from '@/store/user'
import $request from '@/fetch/request.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [...routes, ...exception],
})

const checkPermission = (resources, permission) => {
  if (permission) {
    for (const resource of resources) {
      // 如果当前资源的 resourceKey 匹配并且存在 permission 属性
      if (typeof permission === 'string' && resource.resourceKey === permission) {
        return false
      }
      if (Array.isArray(permission) && resource.resourceKey && permission.includes(resource.resourceKey)) {
        return false
      }
      // 如果有子资源，递归检查子资源
      if (resource.children && resource.children.length > 0) {
        const hasPerm = checkPermission(resource.children, permission)
        if (!hasPerm) {
          return hasPerm
        }
      }
    }
    return true
  } else {
    return false
  }
}

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  if (to?.meta?.permission) {
    if (useUserStore()?.menuList?.length) {
      const menuList = useUserStore()?.menuList || []
      if (checkPermission(menuList || [], to?.meta?.permission || null)) {
        next('/403')
      }
    } else {
      await useUserStore().getUserInfo()
      const menuList = useUserStore()?.menuList || []
      if (checkPermission(menuList || [], to?.meta?.permission || null)) {
        next('/403')
      }
    }
  }
  next() // 继续导航
})

export default router
